import { Injectable, UseFilters, UseGuards } from '@nestjs/common';
import { WebSocketGateway, SubscribeMessage, WsResponse, WebSocketServer, WsException, OnGatewayConnection, OnGatewayInit, OnGatewayDisconnect } from '@nestjs/websockets';
// import { NestGateway } from '@node_modules/@nestjs/websockets/interfaces/nest-gateway.interface.d.ts'
import Socket = SocketIO.Socket;

@Injectable()
@WebSocketGateway(81, { namespace: 'msg' })
export class TestGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {

    public socket: Socket;
    // 外部调用socket
    @WebSocketServer() private server: any;

    constructor() {
    }

    afterInit(server) {

    }

    // 连接建立完成时生命钩子
    public async handleConnection(socket) {
        socket.emit('fromServerMsg', 'hello, browser.')
        // this.serverToClient()
    }

    // 断开连接时生命钩子
    public handleDisconnect(socket): any {
        socket.emit('fromServerMsg', 'bye, browser.')
    }

    public serverToClient(msg) {
        this.server.emit('fromServerMsg', msg)
    }

    //訂閱pushMessage事件
    @SubscribeMessage('pushMessage')
    AddMessage(sender, message: string) {
        let msg = "I'm server."
        //推訊息給自己的前端畫面。
        console.log(message)
        sender.emit('newMessage', msg);
        //推訊息給其他已建立連線的前端畫面。
        sender.broadcast.emit('newMessage', msg);
    }
}
